﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using System.Net.Sockets;

namespace ControlClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        SocketClient client;
        int speed = 0;
        MoveType[] moveac = new MoveType[2];
        string movestr = "";
        int isAuto = 0;

        /// <summary>
        /// 机车移动类型
        /// </summary>
        enum MoveType
        {
            W,D,L,R,S
        }

        public MainWindow()
        {
            InitializeComponent();
            moveac[0] = MoveType.S;
            moveac[1] = MoveType.S;
            imgstart.Source = new BitmapImage(new Uri("pack://application:,,,/img/red.jpg"));
            client = new SocketClient();
            client.Recevie_Even = Receive_Completed;
            Timer timer = new Timer(new TimerCallback(CheckStart));
            timer.Change(10, 1000 * 20);
        }

        /// <summary>
        /// 定时监控网络状态
        /// </summary>
        /// <param name="obj"></param>
        private void CheckStart(object obj)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate {
                if (client.Connectioned)
                {
                    imgstart.Source = new BitmapImage(new Uri("pack://application:,,,/img/green.jpg"));
                }
                else
                {
                    imgstart.Source = new BitmapImage(new Uri("pack://application:,,,/img/red.jpg"));
                }
            });
        }


        /// <summary>
        /// 机车前进
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_w_Click(object sender, RoutedEventArgs e)
        {
            moveac[0]=MoveType.W;
            moveac[1] = MoveType.S;
            ControlSend();
        }

        /// <summary>
        /// 机车左转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_L_Click(object sender, RoutedEventArgs e)
        {
            moveac[0] = MoveType.S;
            moveac[1] = MoveType.L;
            ControlSend();
        }

        /// <summary>
        /// 机车后退
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_D_Click(object sender, RoutedEventArgs e)
        {
            moveac[0] = MoveType.D;
            moveac[1] = MoveType.S;
            ControlSend();
        }

        /// <summary>
        /// 机车右转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_R_Click(object sender, RoutedEventArgs e)
        {
            moveac[0] = MoveType.S;
            moveac[1] = MoveType.R;
            ControlSend();
        }

        /// <summary>
        /// 机车止步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnstop_Click(object sender, RoutedEventArgs e)
        {
            moveac[0] = MoveType.S;
            moveac[1] = MoveType.S;
            ControlSend();
        }

        /// <summary>
        /// 调速器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void slider_speed_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            speed = (int)e.NewValue;
        }

        /// <summary>
        /// 从新链接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void connection_Click(object sender, RoutedEventArgs e)
        {
            bool isconn= client.Connection();
            if (isconn)
            {
                imgstart.Source = new BitmapImage(new Uri("pack://application:,,,/img/green.jpg"));
            }
        }

        /// <summary>
        /// 退出客户端事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnexit_Click(object sender, RoutedEventArgs e)
        {
            client.SendAsync("cmd$control01$out", SendAsync_Completed);
        }

        /// <summary>
        /// 退出客户端后处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendAsync_Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                client.Close();
            }
        }

        /// <summary>
        /// 按键按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            slider_speed.IsEnabled = false;
            if (e.Key == Key.W||e.Key==Key.Up)
            {
                moveac[0] = MoveType.W;
            }
            else if (e.Key == Key.S||e.Key==Key.Down)
            {
                moveac[0] = MoveType.D;
            }
            else if (e.Key == Key.A||e.Key==Key.Left)
            {
                moveac[1] = MoveType.L;
            }
            else if (e.Key == Key.D||e.Key==Key.Right)
            {
                moveac[1] = MoveType.R;
            }
            ControlSend();
        }

        /// <summary>
        /// 按键抬起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            slider_speed.IsEnabled = true;
            if (e.Key == Key.W || e.Key == Key.Up || e.Key == Key.S || e.Key == Key.Down)
            {
                moveac[0] = MoveType.S;
            }
            else if (e.Key == Key.A || e.Key == Key.Left || e.Key == Key.D || e.Key == Key.Right)
            {
                moveac[1] = MoveType.S;
            }
            ControlSend();
        }

        /// <summary>
        /// 处理机车移动
        /// </summary>
        private void ControlSend()
        {
            int[] move = new int[4];
            if (moveac[0] == MoveType.W && moveac[1] == MoveType.S)
            {
                move[0] = 0;
                move[1] = speed;
                move[2] = 0;
                move[3] = speed;
            }
            else if (moveac[0] == MoveType.W && moveac[1] == MoveType.L)
            {
                move[0] = speed;
                move[1] = 0;
                move[2] = 0;
                move[3] = speed;
            }
            else if (moveac[0] == MoveType.W && moveac[1] == MoveType.R)
            {
                move[0] = 0;
                move[1] = speed;
                move[2] = speed;
                move[3] = 0;
            }
            else if (moveac[0] == MoveType.D && moveac[1] == MoveType.S)
            {
                move[0] = speed;
                move[1] = 0;
                move[2] = speed;
                move[3] = 0;
            }
            else if (moveac[0] == MoveType.D && moveac[1] == MoveType.L)
            {
                move[0] = 0;
                move[1] = speed;
                move[2] = speed;
                move[3] = 0;
            }
            else if (moveac[0] == MoveType.D && moveac[1] == MoveType.R)
            {
                move[0] = speed;
                move[1] = 0;
                move[2] = 0;
                move[3] = speed;
            }
            else if (moveac[0] == MoveType.S && moveac[1] == MoveType.L)
            {
                move[0] = 0;
                move[1] = 0;
                move[2] = 0;
                move[3] = speed;
            }
            else if (moveac[0] == MoveType.S && moveac[1] == MoveType.R)
            {
                move[0] = 0;
                move[1] = speed;
                move[2] = 0;
                move[3] = 0;
            }
            else
            {
                move[0] = 0;
                move[1] = 0;
                move[2] = 0;
                move[3] = 0;
            }
            var tempstr = string.Join(",",move) ;
            if (!tempstr.Equals(movestr))
            {
                movestr = tempstr;
                client.SendAsync("move$control01$tankcart02|" + movestr, null);
            }
        }

        /// <summary>
        /// 监控服务端套接字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Receive_Completed(object sender, SocketAsyncEventArgs e)//msg$tankcart01$Hello Word!!!!!!!!!!!
        {
            string req = sender as string;
            req = req.Substring(0, req.IndexOf("\0"));//msg$tankcart01$radal|1|200
            if (string.IsNullOrEmpty(req))
            {
                return;
            }
            var cmd = req.Split('$');
            switch (cmd[0])
            {
                case "msg":
                    ShowMsg(cmd[1],cmd[2]);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="form"></param>
        /// <param name="msg"></param>
        private void ShowMsg(string form, string msg)//radal|1|200   radal|1|8.56
        {
            var val = msg.Split('|');
            switch (val[0])
            {
                case"radal":
                    ShowRadal(form,Convert.ToInt32(val[1]),Convert.ToDouble(val[2]));
                    break;
                case "sand":
                    ShowSand(form,val[1]);
                    break;
                default:
                    ShowSand(form, msg);
                    break;
            }
            ShowSand(form, msg);
        }

        private void ShowRadal(string form,int num,double distance)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate {
                txtzaw.Text = string.Format("{0}{1}号雷达距离前方障碍物：{2}厘米",form,num,distance);
            });
        }

        private void ShowSand(string form, string msg)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
            {
                textshow.Text = string.Format("{0}说：{1}", form,msg);
            });
        }

        private void btnIsauto_Click(object sender, RoutedEventArgs e)
        {
            var cmd = isAuto * -1 + 1;
            client.SendAsync("cmd$control01$tankcart01$auto|" + cmd, BtnIsauto_Completed);
        }

        private void BtnIsauto_Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                isAuto = isAuto * -1 + 1;
            }
        }
        
    }
}
